package com.zhugang.week05;

import java.util.HashMap;
import java.util.Map;

/**
 * @program algorithms
 * @description: checkPermutation
 * @author: chanzhugang
 * @create: 2022/07/08 16:00
 */
public class CheckPermutation2 {

    /**
     * 面试题 01.02 判定是否互为字符重排
     *
     * @param s1
     * @param s2
     * @return
     */
    public boolean checkPermutation(String s1, String s2) {
        // 哈希表， s1放入哈希表中，遍历s2是否在哈希表
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            int count = 1;
            if (map.containsKey(c)) {
                count += map.get(c);
            }
            map.put(c, count);
        }

        for (int i = 0; i < s2.length(); i++) {
            char c = s2.charAt(i);
            if (!map.containsKey(c)) {
                return false;
            }
            Integer count = map.get(c);
            if (count == 0) {
                return false;
            }
            map.put(c, count - 1);
        }

        // 检查map是否还有值
        for (int i = 0; i < s1.length(); i++) {
            char c = s1.charAt(i);
            if (map.get(c) != 0) {
                return false;
            }
        }
        return true;
    }
}